package com.ck567.springbootnettyprotobufjava.dispatcher;

import com.ck567.springbootnettyprotobufjava.handler.MessageHandler;
import com.ck567.springbootnettyprotobufjava.message.Message;
import com.ck567.springbootnettyprotobufjava.server.MessageHandlerContainer;
import com.ck567.springbootnettyprotobufjava.utils.ThreadPool;
import com.google.protobuf.MessageLite;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @description: 消息分发器
 */
@ChannelHandler.Sharable
@Component
public class MessageDispatcher extends SimpleChannelInboundHandler<Message> {

    private final MessageHandlerContainer container;

    private final ThreadPool threadPool;

    @Autowired
    public MessageDispatcher(MessageHandlerContainer container, ThreadPool threadPool) {
        this.container = container;
        this.threadPool = threadPool;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
        MessageHandler<MessageLite> handler = container.getHandler(msg.getType());
        threadPool.threadPoolExecutor().execute(() -> handler.execute(ctx.channel(), msg.getMsg()));
    }
}
